package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.EmployeeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import java.time.LocalDateTime;

@Service
@Transactional//开启事务
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // TODO 后期需要进行md5加密，然后再进行比对

        //密码加密校验
        String pwd = DigestUtils.md5DigestAsHex(password.getBytes());

        if (!pwd.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    /**
     * 添加员工
     * @param dto
     */
    @Override
    @Transactional//事务
    public Result addEmp(EmployeeDTO dto) {
        //参数处理判空
        if (dto.getUsername()==null){
            //账号为空
            return Result.error(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //调用dao查询用户是否已存在
        Employee byUsernameEmp = employeeMapper.getByUsername(dto.getUsername());

        if (byUsernameEmp != null){
            return Result.error(MessageConstant.ACCOUNT_EXISTS_FOUND);
        }

        Employee employee = new Employee();
        //拷贝dto数据到实体类
        BeanUtils.copyProperties(dto,employee);

        //补全数据,默认密码,状态status,createTime,updateTime,createUser,updateUser
        employee.setStatus(StatusConstant.DISABLE);
        employee.setPassword(PasswordConstant.DEFAULT_PASSWORD);
        /* 以后在切面类完成添加操作
        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());
        employee.setCreateUser(BaseContext.getCurrentId());
        employee.setUpdateUser(BaseContext.getCurrentId());*/


        //调用dao层
        employeeMapper.addEmp(employee);

        //返回数据
        return Result.success();


    }

    /**
     * 分页查询
     * @param dto
     * @return
     */
    @Override
    public Result page(EmployeePageQueryDTO dto) {
        //处理参数
        if (dto.getPage() == null){
            dto.setPage(1);
        }
        if (dto.getPageSize() == null){
            dto.setPageSize(10);
        }

        //开启分页
        PageHelper.startPage(dto.getPage(), dto.getPageSize());

        //调用dao
        Page<Employee> employeePage = employeeMapper.page(dto);

        //添加参数到PageResult中返回

        PageResult pageResult = new PageResult();
        pageResult.setTotal(employeePage.getTotal());
        pageResult.setRecords(employeePage.getResult());

        return Result.success(pageResult);
    }

    /**
     * 员工状态修改
     *
     * @param status
     * @param id
     */
    @Override
    @Transactional//加事务注解
    public Result updateStatus(Integer status, Long id) {
        //处理参数
        if (status == null){
            return Result.error(MessageConstant.STATUS_EXISTS_FOUND);
        }
        if (id == null){
            return Result.error(MessageConstant.ID_EXISTS_FOUND);
        }

        //封装处理参数补全修改参数
        Employee employee = new Employee();
        employee.setId(id);
        employee.setStatus(status);
        /*以后在切面类完成添加操作
        employee.setUpdateTime(LocalDateTime.now());
        employee.setUpdateUser(BaseContext.getCurrentId());*/


        //调用dao修改状态
        employeeMapper.update(employee);

        return Result.success();

    }

    /**
     * 根据id查询员工
     *
     * @param id
     * @return
     */
    @Override
    public Employee getById(Integer id) {
        //处理参数
        if (id == null){
            throw new RuntimeException(MessageConstant.ID_EXISTS_FOUND);
        }

        //调用dao
        Employee employee = employeeMapper.getById(id);

        return employee;
    }

    /**
     * 修改员工
     *
     * @param dto
     */
    @Override
    public void updateEmp(EmployeeDTO dto) {
        //处理参数
        if (dto.getId() == null){
            throw new RuntimeException(MessageConstant.ID_EXISTS_FOUND);
        }

        //拷贝代码到Employee,再传入dao进行修改\
        Employee employee = new Employee();
        BeanUtils.copyProperties(dto , employee);
        /*//补全参数  以后在切面类完成添加操作
        employee.setUpdateTime(LocalDateTime.now());
        employee.setUpdateUser(BaseContext.getCurrentId());*/


        //调用dao
        employeeMapper.update(employee);

    }

}
